<template>
  <a-modal :width="1200" v-model:visible="showToProductDialog" title="转产品库" title-align="start" :mask-closable="false" :on-before-ok="submitData" :ok-loading="submitLoading" @cancel="closedDialog">
    <div class="table-model-wrap">
      <a-table size="mini" :data="productList" :scroll="{ y: 'calc(84vh - 160px)' }" :bordered="false" class="table-two-line table-model" :pagination="false">
        <template #columns>
          <a-table-column title="" :width="35">
            <template #cell="{ rowIndex }">
              <p>{{ rowIndex + 1 }}</p>
            </template>
          </a-table-column>
          <a-table-column title="图片" :width="60">
            <template #cell="{ record }">
              <ImgPopover :src="getMainUrl(record)">
                <template #con>
                  <a-image width="50" height="50" fit="contain" :src="getMainUrl(record)" />
                </template>
              </ImgPopover>
            </template>
          </a-table-column>
          <a-table-column title="商品标题/MSKU" :width="220">
            <template #cell="{ record }">
              <a-popover position="tl" style="width: 400px">
                <p class="text-limit-two">{{ record.name }}</p>
                <template #content>
                  <p>{{ record.name }}</p>
                </template>
              </a-popover>
              <p style="margin-top: 6px">{{ record.msku }}</p>
            </template>
          </a-table-column>
          <a-table-column :width="120">
            <template #title>
              <span class="warningColor">*</span>
              <span>品类</span>
            </template>
            <template #cell="{ record, rowIndex }">
              <div class="flex-c">
                <a-cascader v-model="record.categoryId" size="small" :options="categoryList" :path-mode="false" :format-label="format" :field-names="{ value: 'id', label: 'name' }" style="width: 80px; margin-right: 4px" allow-clear allow-search placeholder="品类" check-strictly />
                <a-button size="small" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'categoryId')">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </div>
            </template>
          </a-table-column>
          <a-table-column :width="210">
            <template #title>
              <span class="warningColor">*</span>
              <span>SPU</span>
            </template>
            <template #cell="{ record, rowIndex }">
              <div class="flex-c">
                <a-input v-model="record.spu" size="small" style="width: 130px" allow-clear allow-search />
                <a-button size="small" style="padding: 0 6px; margin-right: 4px" type="primary" @click="openChooseSpu(rowIndex)">选择</a-button>
                <a-button size="small" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'spu')">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </div>
            </template>
          </a-table-column>
          <a-table-column :width="155">
            <template #title>
              <span class="warningColor">*</span>
              <span>SKU</span>
            </template>
            <template #cell="{ record }">
              <a-input v-model="record.sku" size="small" style="width: 140px" allow-clear allow-search />
            </template>
          </a-table-column>
          <a-table-column title="产品开发员" :width="125">
            <template #cell="{ record, rowIndex }">
              <div class="flex-c">
                <a-select v-model="record.developer" size="small" style="width: 80px; margin-right: 4px" value-key="id" placeholder="请选择" allow-search allow-clear>
                  <a-option v-for="(user, i) in userList" :key="i" :value="user" :label="user.userName" />
                </a-select>
                <a-button size="small" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'developer')">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="销售员" :width="230">
            <template #cell="{ record, rowIndex }">
              <div class="flex-c">
                <a-select v-model="record.salerList" multiple :max-tag-count="1" size="small" style="width: 180px; margin-right: 4px" value-key="id" placeholder="请选择" allow-search allow-clear>
                  <a-option v-for="(user, i) in userList" :key="i" :value="user" :label="user.userName" />
                </a-select>
                <a-button size="small" class="gray-outline" v-if="rowIndex === 0" @click="setGlobal(record, 'salerList')">
                  <template #icon>
                    <icon-double-down />
                  </template>
                </a-button>
              </div>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
  </a-modal>
  <!-- 选择产品 -->
  <ChooseProductSpu v-if="showChooseProductDialog" title="选择SPU" :isShow="showChooseProductDialog" @closed="showChooseProductDialog = false" @success="chooseProduct" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, PropType } from 'vue'
  import ImgPopover from '@/components/imgPopover.vue'
  import { getCategoryList } from '@/api/product'
  import { convertProductBatch } from '@/api/publish'
  import { findChildrenArray } from '@/utils/index'
  import { Message } from '@arco-design/web-vue'
  import ChooseProductSpu from './chooseProductSpu.vue'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    currentList: {
      type: Array,
      default: () => [],
    },
    userList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
  })
  onMounted(async () => {
    setProductList()
    getCategorys()
  })

  const showToProductDialog = ref(props.isShow)
  const submitLoading = ref(false)
  const categoryList = ref([])
  const showChooseProductDialog = ref(false)
  const productList = ref<Array<any>>([])
  let currentIndex = 0

  // 显示图片
  function getMainUrl(row: any) {
    return row?.imageList?.[0]?.link
  }
  // 获取产品类目
  async function getCategorys() {
    const res: any = await getCategoryList()
    categoryList.value = res?.data || []
  }
  //设置转产品库数据
  function setProductList() {
    productList.value = props.currentList.map((el: any) => {
      let item = JSON.parse(JSON.stringify(el))
      item.sku = item?.product?.sku || item.msku
      // 没有父ASIN的,SPU默认是SKU，有父ASIN取父ASIN的sku或msku
      item.spu = item?.parent?.sku || item?.parent?.msku || item.sku || item.msku
      item.categoryId = item?.category?.id
      return item
    })
  }
  function format(options: any) {
    const labels = options.map((option: any) => option.name)
    return labels?.[labels.length - 1]
  }
  // 关闭
  function closedDialog() {
    showToProductDialog.value = false
    emit('closed')
  }

  // 提交
  async function submitData() {
    // 需要先教研必填参数，再请求接口
    let products: Array<any> = []
    let noSku = productList.value.some((el: any) => !el.sku || !el.spu)
    if (noSku) {
      Message.error('SKU，SPU必填')
      return false
    }
    productList.value.forEach((el: any) => {
      let obj: any = {
        sku: el.sku,
        spu: el.spu,
        amzProductSaleId: el.id,
      }
      // 销售员
      if (el.salerList?.length) {
        obj.salerList = el.salerList.map((user: any) => {
          return {
            id: user.id,
            name: user.userName,
          }
        })
      }
      // 开发者
      if (el.developer?.id) {
        obj.developer = {
          id: el.developer.id,
          name: el.developer.userName,
        }
      }
      // 类目
      if (el.categoryId) {
        let info = findChildrenArray(categoryList.value, el.categoryId, 'id')
        if (info) {
          obj.category = {
            id: info?.id,
            name: info?.name,
          }
        }
      }
      products.push(obj)
    })
    const res: any = await convertProductBatch({
      list: products,
    })
    if (res) {
      Message.success('批量转产品库成功')
      emit('success')
      closedDialog()
      return true
    }
    return false
  }
  // 打开选择SPU
  function openChooseSpu(index: number) {
    currentIndex = index
    showChooseProductDialog.value = true
  }
  // 选择spu
  async function chooseProduct(product: any) {
    productList.value[currentIndex].spu = product.spu
  }
  //设置全局
  function setGlobal(item: any, key: string) {
    let val = item[key]
    productList.value.forEach((el) => {
      el[key] = val
    })
  }
</script>
<style lang="less" scoped>
  .info-text {
    color: #999;
    margin-top: 10px;
  }
  :deep(.arco-table-cell) {
    padding: 2px 4px;
    .arco-input-wrapper {
      padding: 2px 6px;
    }
    .arco-input.arco-input-size-small {
      font-size: 12px;
    }
    .arco-select-view-size-small {
      padding: 0 6px;
      font-size: 12px;
    }
    .arco-select-view-input,
    .arco-select-view-value {
      font-size: 12px;
      min-height: 26px;
      line-height: 1.5715;
    }
    .arco-select-view-multiple .arco-select-view-input {
      min-height: 20px;
    }
  }
</style>
